import asyncio
import traceback
from typing import Any, Dict

from app.core.constants import ExecutorType, TaskStatus, TriggerType
from app.core.task.scheduler import Scheduler
from app.core.task.store.redis import RedisStore
from app.core.task.task_log import scheduler_logger
from app.core.task.task_manager import TaskManager
from app.models.job_model import JobExecutionLogModel, JobModel


async def sync_execution_log_with_db() -> Dict[str, Any]:
    """同步任务执行记录到数据库"""

    try:
        store = RedisStore()
        execution_logs = await store.get_job_execution_logs()
        objs = []
        for log in execution_logs:
            obj = JobExecutionLogModel(**log.model_dump())
            objs.append(obj)
        await JobExecutionLogModel.bulk_create(objs)
    except Exception as e:
        error_message = traceback.format_exc()
        print(error_message)
        return {
            "message": "同步任务执行记录失败",
            "total": 0,
            "success": False,
            "error": error_message,
        }

    return {
        "message": "同步任务执行记录成功",
        "total": len(execution_logs),
        "success": True,
        "error": None,
    }


async def start_scheduler() -> Scheduler:
    """初始化调度器"""

    # 删除全部任务
    # await JobModel.all().delete()
    if not await JobModel.filter(name="同步任务执行记录").exists():
        await JobModel.create(
            name="同步任务执行记录",
            executor_type=ExecutorType.MODULE,
            module_path="app.core.task.scheduler_manager",
            function_name="sync_execution_log_with_db",
            trigger_type=TriggerType.INTERVAL,
            trigger_args={"interval_seconds": 30},
            priority=1,
            status=TaskStatus.ACTIVE,
            args=[],
            kwargs={},
            timeout=10,
        )

    # 创建调度器实例
    scheduler = Scheduler()

    # 初始化调度器
    asyncio.create_task(scheduler.start())
    await TaskManager().sync_db_with_redis()
    scheduler_logger.info("调度器已启动")


async def stop_scheduler():
    """停止调度器"""
    scheduler = Scheduler.get_instance()
    await scheduler.shutdown()
    scheduler_logger.info("调度器已停止")
